//! \file check.h

#include <stdio.h>
#include <stdlib.h>
#include "errors.h"

//------------------------------------------------------------------------------

#ifndef _CHECK_H_
#define _CHECK_H_

//------------------------------------------------------------------------------

#define CHECK(expr) \
    do { \
        if (!(expr)) { \
            fprintf(stderr, "CHECK failed: \"%s\" at %s:%d\n", \
                    #expr, __FILE__, __LINE__); \
            abort(); \
        } \
    } while(0)

//------------------------------------------------------------------------------

#define CHECK_ERR(expr, error) \
    do { \
        if (!(expr)) { \
            fprintf(stderr, "CHECK: expr: \"%s\" error: \"%s\" at %s:%d\n", \
                    #expr, StrError(error), __FILE__, __LINE__); \
            abort(); \
        } \
    } while(0)

//------------------------------------------------------------------------------

#ifdef NDEBUG
#define CHECK_DBG(expr)
#define CHECK_DBG_ERR(expr, err)
#else 
#define CHECK_DBG(expr) CHECK(expr)
#define CHECK_DBG_ERR(expr, err) CHECK_ERR(expr, err)
#endif

//------------------------------------------------------------------------------

#define CHECK_RET(expr, error, exit_label, ret_var) \
    do { \
        if (!(expr)) { \
            fprintf(stderr, "CHECK failed with error (%s): \"%s\" at " \
                    "%s:%d\n", StrError(error), #expr, __FILE__, \
                    __LINE__); \
            ret_var = error; \
            goto exit_label; \
        } \
    } while(0)

//------------------------------------------------------------------------------

#define CHECK_CALL(expr, exit_label, ret_var) \
    do { \
        TBGError __err = expr; \
        if (__err) { \
            fprintf(stderr, "CHECK CALL failed with error (%s): \"%s\" at " \
                    "%s:%d\n", StrError(__err), #expr, __FILE__, __LINE__); \
            ret_var = __err; \
            goto exit_label; \
        } \
    } while(0)

//------------------------------------------------------------------------------

#endif //_CHECK_H_
